from app import app, db
from models import User, Order, Product, Tag, UserTag, OrderItem
from datetime import datetime, timedelta
import random
import string
import json

def generate_random_name():
    first_names = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴']
    last_names = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '洋']
    return random.choice(first_names) + random.choice(last_names)

def generate_random_email(username):
    domains = ['gmail.com', 'yahoo.com', 'hotmail.com', '163.com', 'qq.com']
    random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
    return f"{username}_{random_str}@{random.choice(domains)}"

def generate_random_phone():
    return f"1{random.choice(['3', '5', '7', '8', '9'])}" + ''.join(random.choices(string.digits, k=9))

def generate_test_data():
    # 清空现有数据
    db.session.query(OrderItem).delete()
    db.session.query(Order).delete()
    db.session.query(UserTag).delete()
    db.session.query(User).delete()
    db.session.query(Product).delete()
    db.session.commit()
    
    # 创建产品
    products = []
    categories = ['客房', '餐饮', '休闲', '会议']
    for i in range(20):
        category = random.choice(categories)
        if category == '客房':
            name = random.choice(['标准间', '大床房', '豪华套房', '商务套房', '总统套房'])
            price = random.uniform(300, 3000)
        elif category == '餐饮':
            name = random.choice(['早餐', '午餐', '晚餐', '下午茶', '宵夜'])
            price = random.uniform(50, 300)
        elif category == '休闲':
            name = random.choice(['游泳', '健身', 'SPA', '桑拿', '按摩'])
            price = random.uniform(100, 500)
        else:
            name = random.choice(['小型会议室', '中型会议室', '大型会议室', '宴会厅', '多功能厅'])
            price = random.uniform(1000, 5000)
            
        product = Product(name=f"{name}", category=category, price=price)
        db.session.add(product)
        products.append(product)
    
    db.session.commit()
    
    # 创建用户和订单
    membership_levels = ['普通会员', '银卡会员', '金卡会员', '钻石会员']
    now = datetime.now()
    
    # 获取所有标签
    value_tags = Tag.query.filter_by(category='用户价值').all()
    activity_tags = Tag.query.filter_by(category='活跃度').all()
    type_tags = Tag.query.filter_by(category='客户类型').all()
    
    for i in range(100):  # 创建100个用户
        username = generate_random_name()
        registration_date = now - timedelta(days=random.randint(30, 365))  # 确保用户至少注册30天
        last_login = min(now, registration_date + timedelta(days=random.randint(0, 30)))
        
        user = User(
            username=username,
            email=generate_random_email(username),
            phone=generate_random_phone(),
            membership_level=random.choice(membership_levels),
            registration_date=registration_date,
            last_login=last_login,
            consumption_score=random.uniform(0, 1000),
            status=random.choice([True, True, True, False])  # 75%的用户是活跃状态
        )
        db.session.add(user)
        db.session.flush()  # 获取用户ID
        
        # 为每个用户创建1-10个订单
        order_count = random.randint(1, 10)
        total_consumption = 0
        for j in range(order_count):
            # 生成一个在注册日期和当前日期之间的随机日期
            days_since_registration = (now - registration_date).days
            if days_since_registration > 0:
                order_date = registration_date + timedelta(days=random.randint(1, days_since_registration))
                
                order = Order(
                    user_id=user.id,
                    order_date=order_date,
                    status='completed',
                    total_amount=0  # 将在添加订单项后更新
                )
                db.session.add(order)
                db.session.flush()  # 获取订单ID
                
                # 为每个订单添加1-5个商品
                total_amount = 0
                order_items = []
                item_count = random.randint(1, 5)
                selected_products = random.sample(products, item_count)
                
                for product in selected_products:
                    quantity = random.randint(1, 3)
                    price = float(product.price)
                    order_item = OrderItem(
                        order_id=order.id,
                        product_id=product.id,
                        quantity=quantity,
                        price=price
                    )
                    total_amount += price * quantity
                    order_items.append(order_item)
                    db.session.add(order_item)
                
                # 更新订单总金额
                order.total_amount = total_amount
                total_consumption += total_amount
                
                # 添加订单项的JSON数据
                order.items = json.dumps([{
                    'product_id': item.product_id,
                    'quantity': item.quantity,
                    'price': float(item.price)
                } for item in order_items])
        
        # 更新用户的消费得分
        user.consumption_score = total_consumption / 100  # 消费得分为总消费的1%
        
        # 添加用户标签
        # 1. 价值标签
        if total_consumption > 10000:
            high_value_tag = next((tag for tag in value_tags if tag.name == '高价值客户'), None)
            if high_value_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=high_value_tag.id))
        
        if user.membership_level in ['金卡会员', '钻石会员']:
            vip_tag = next((tag for tag in value_tags if tag.name == 'VIP会员'), None)
            if vip_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=vip_tag.id))
        
        # 2. 活跃度标签
        if user.is_active:
            active_tag = next((tag for tag in activity_tags if tag.name == '活跃客户'), None)
            if active_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=active_tag.id))
        elif user.is_churn:
            churn_tag = next((tag for tag in activity_tags if tag.name == '流失客户'), None)
            if churn_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=churn_tag.id))
        else:
            potential_tag = next((tag for tag in activity_tags if tag.name == '潜在客户'), None)
            if potential_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=potential_tag.id))
        
        # 3. 客户类型标签
        if (now - registration_date).days <= 30:
            new_tag = next((tag for tag in type_tags if tag.name == '新注册用户'), None)
            if new_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=new_tag.id))
        
        if order_count >= 5:
            regular_tag = next((tag for tag in type_tags if tag.name == '常住客户'), None)
            if regular_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=regular_tag.id))
        
        # 随机分配商务/休闲标签
        if random.random() < 0.3:  # 30%的概率是商务客户
            business_tag = next((tag for tag in type_tags if tag.name == '商务客户'), None)
            if business_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=business_tag.id))
        else:
            leisure_tag = next((tag for tag in type_tags if tag.name == '休闲客户'), None)
            if leisure_tag:
                db.session.add(UserTag(user_id=user.id, tag_id=leisure_tag.id))
    
    db.session.commit()
    print("测试数据生成完成！")

if __name__ == '__main__':
    with app.app_context():
        generate_test_data()
